package com.boarsoft.log.core;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.MDC;

import com.boarsoft.common.Util;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.UnsynchronizedAppenderBase;

/**
 * 
 * @author Mac_J
 *
 */
public class SampleLogAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
	// public class SampleLogAppender extends AsyncAppenderBase<ILoggingEvent> {
	/** */
	protected Layout<ILoggingEvent> layout;
	/** */
	protected String target;

	@Override
	public void start() {
		if (layout == null) {
			addWarn("Layout is not defined");
		}
		super.start();
	}

	@Override
	protected void append(ILoggingEvent event) {
		if (event == null || !isStarted()) {
			return;
		}
		if (!event.getLevel().isGreaterOrEqual(Level.INFO)) {
			return;
		}
		// traceId = taskId
		String traceId = MDC.get("trace");
		if (Util.strIsEmpty(traceId)) {
			return;
		}
		// 调用消息API，发送点对点消息到监控，完成采样
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("target", target);
		m.put("key", traceId);
		m.put("time", event.getTimeStamp());
		if (layout == null) {
			m.put("content", event.getMessage());
		} else {
			m.put("content", layout.doLayout(event));
		}
		try {
			SampleLogSender.send(m);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public void setLayout(Layout<ILoggingEvent> layout) {
		this.layout = layout;
	}

	public Layout<ILoggingEvent> getLayout() {
		return layout;
	}
}
